package run.siyuan.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.DatePrinter;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import run.siyuan.mapper.SignRecordMapper;
import run.siyuan.model.SignRecord;

import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Formatter;
import java.util.List;

/**
 * @className: SignService
 * @Description: TODO
 * @author: siyuan
 * @date: 2023/2/20 11:18
 */
@Service
public class SignRecordService extends ServiceImpl<SignRecordMapper, SignRecord> {

    private String SIGN_KEY = "sign:";

    @Autowired
    private RedisTemplate redisTemplate;

    public Object sign(Long userId, Date date) {
        String yearMonth = DateUtil.format(date, DatePattern.SIMPLE_MONTH_PATTERN);
        int day = DateUtil.dayOfMonth(date);
        String key = SIGN_KEY + userId + ":" + yearMonth;
        Boolean signB = redisTemplate.opsForValue().getBit(key, day - 1);
        if (signB) {
            return "今日已签到";
        }
        // 未签到
        DateTime now = DateUtil.date();
        SignRecord record = new SignRecord();
        record.setUserId(userId);
        record.setSignYear(DateUtil.year(date));
        record.setSignMonth(DateUtil.month(date) + 1);
        record.setSignDate(now);
        record.setCreateTime(now);
        record.setUpdateTime(now);
        baseMapper.insert(record);

        redisTemplate.opsForValue().setBit(key, day - 1, true);

        return true;
    }

    /**
     * 本月一共签到次数
     *
     * @param userId
     * @param date
     * @return
     */
    public int bigFist(Long userId, Date date) {
        String yearMonth = DateUtil.format(date, DatePattern.SIMPLE_MONTH_PATTERN);
        int day = DateUtil.dayOfMonth(date);
        String key = SIGN_KEY + userId + ":" + yearMonth;
        List<Long> result = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));
        System.out.println(result.toString());

        //没有任务签到结果
        if (result == null || result.isEmpty()) {
            return 0;
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return 0;
        }
        //6. 循环遍历
        int count = 0;
        while (true) {
            //6.1 让这个数字与1 做与运算，得到数字的最后一个bit位 判断这个数字是否为0
            if ((num & 1) == 0) {
                //如果为0，签到结束
                break;
            } else {
                count++;
            }
            num >>>= 1;
        }
        return count;
    }


    /**
     * 连续签到次数
     */
    public int continuousSignCount(Long userId, Date date) {
        String yearMonth = DateUtil.format(date, DatePattern.SIMPLE_MONTH_PATTERN);
        int day = DateUtil.dayOfMonth(date);
        String key = SIGN_KEY + userId + ":" + yearMonth;
        List<Long> result = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));

        //没有任务签到结果
        if (result == null || result.isEmpty()) {
            return 0;
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return 0;
        }
        Long signFlag = result.get(0) == null ? 0 : result.get(0);
        if (signFlag == 0) {
            return 0;
        }
        int signCount = 0;
        for (int i = 0; i < day; i++) {

            if (signFlag >> 1 << 1 == signFlag) {
                if (i > 0) {
                    break;
                }
            } else {
                signCount += 1;
            }
            signFlag >>= 1;
        }
        return signCount;
    }


}
